<?php

namespace app\teacher\controller\grammar;

use app\common\controller\Frontend;
use app\common\enums\CategoryStateEnum;
use app\common\service\grammar\DetectionService;
use app\common\model\banxi\grammar\GrammarCategory as GrammarCategoryModel;
use app\common\model\banxi\grammar\GrammarLearn;
use think\db\exception\DbException;

class GrammarCategory extends Frontend
{
    protected array $noNeedLogin = [''];

    protected array $noNeedPermission = ['*'];

    public function initialize(): void
    {
        parent::initialize();
    }

    /*
     * 查询-语法页面基础信息
     * */
    public function getGrammarBasicInfo()
    {
        $userId = $this->request->get('userId', 0);
        $gradeId = $this->request->get('gradeId', 0);

        $DetectionService = new DetectionService();
        $data = $DetectionService->getPageBasicInfo($userId, $gradeId);
        $this->ok('操作成功', $data);
    }

    /**
     * 查询-语法分类
     *
     * @param Request $request
     * @return array
     */
    public function listCategory()
    {
        $gradeId = $this->request->get('gradeId');
        $userId = $this->request->get('userId');

        // 如果没有提供userId，则使用当前用户ID
        if (!$userId) {
            $userId = $this->auth->id; // 需要实现获取当前用户ID的方法
        }

        // 构建查询条件
        $GrammarCategoryModel = new GrammarCategoryModel();
        $categoryList = $GrammarCategoryModel->alias('gc')
            ->leftJoin('banxi_grammar_learn gl', 'gl.categoryId = gc.id AND gl.studentId = ' . $userId)
            ->field('gc.*, gl.learnPace as learnPace')
            ->where('gc.gradeId', $gradeId)
            ->where('gc.state', CategoryStateEnum::E1) // 启用状态
            ->order('gc.level', 'asc')
            ->order('gc.sortNum', 'asc')
            ->order('gc.id', 'desc')
            ->select();

        // 转为父子结构
        $treeList = [];

        // 筛选出一级分类（level=0）
        foreach ($categoryList as $category) {
            if ($category['level'] == 0) {
                $category['childrenList'] = [];
                $treeList[] = $category;
            }
        }

        // 为每个一级分类添加子分类
        foreach ($treeList as &$parentCategory) {
            $childrenList = [];

            // 筛选出当前一级分类的子分类
            foreach ($categoryList as $category) {
                if ($category['parentId'] == $parentCategory['id']) {
                    $childrenList[] = $category;
                }
            }

            // 按sort_num排序子分类
            usort($childrenList, function($a, $b) {
                return $a['sortNum'] <=> $b['sortNum'];
            });

            $parentCategory['childrenList'] = $childrenList;
        }

        $this->ok('操作成功', $treeList);
    }

    /**
     * 查询-分类详情
     *
     * @param int $categoryId 分类id
     * @param int $userId 学员id
     * @return \think\response\Json
     */
    public function getGrammarCategoryInfo()
    {
        $categoryId = $this->request->get('categoryId', 0);
        $userId = $this->request->get('userId', 0);

        // 如果userId为空，则使用当前登录用户ID
        $userId = $userId ? $userId : $this->auth->id;
        // 根据学员ID和分类ID获取学习记录
        $GrammarLearnModel = new GrammarLearn();
        $grammarLearn = $GrammarLearnModel->getGrammarLearnByStudentIdAndCategoryId($userId, $categoryId);

        // 更新学习记录的最后学习时间
        if ($grammarLearn) {
            $updateData = [
                'id' => $grammarLearn['id'],
                'lastLearnTime' => date('Y-m-d H:i:s')
            ];
            $GrammarLearnModel->update($updateData);
        }

        // 获取并返回分类详情
        $GrammarCategoryModel = new GrammarCategoryModel();
        $category = $GrammarCategoryModel->where('id', $categoryId)->find();

        $this->ok('操作成功', $category);
    }

    /**
     * 分页查询
     * @return void
     * @throws DbException
     */
    public function listPage(): void
    {
        $param = $this->request->param(['index', 'limit', 'orderBy', "query", 'searchText' => '']);

        if (!empty($param['searchText'])) {
            $param['query']['LIKE_name'] = $param['searchText'];
        }
        //查询条件解析
        $where = get_query($param);

        //获取分页数据
        $pageParams = get_page_params($param);
        $GrammarCategoryModel = new GrammarCategoryModel();
        $list = $GrammarCategoryModel->getListPage($where, $pageParams['page'], $pageParams['limit']);
        $this->ok('操作成功', result_row($list));
    }
}